(function(){
	var ctx1, ctx2;
	var can_w, can_h;  //画布宽高
	var lastframetime, diffframetime=0; //上一帧动画的时间，两帧的时间差
	var backgroundPic; //背景图片

	var margin_space = 15; //距离四周的间距
	var increse_space;   //增长步长,两条线之间的间距

	var chessBoard = [];  //数组，存储棋盘落子情况
	var chessColor = true;  //棋子颜色， 默认开始为黑色

	var wins_arr = []; //赢法数组
	var win_index = 0;  //赢法种类的索引
	//赢法的统计数组
	var myWin = [];   //我方的
	var computerWin = [];   //计算机方的
	var gameOver = false;  //游戏结束

	var reStart = document.getElementById('restart');
	var winer = document.getElementById('winer');

	var burtyang = {};
	burtyang.init = function(){
		var chess1 = document.getElementById('chess1');
		var chess2 = document.getElementById('chess2');
		ctx1 = chess1.getContext("2d");
		ctx2 = chess2.getContext("2d");
		can_w = chess1.width;  //画布宽
		can_h = chess1.height;  //画布高
		//背景图片
		backgroundPic = new Image(can_w, can_h);
		backgroundPic.src = './images/background.png';

		//增长步长,两条线之间的间距
		increse_space = (can_w- margin_space*2)/15;

		//绘制棋盘,监听资源加载完后绘制
		backgroundPic.addEventListener('load',this.drawChess);

		//点击棋盘落子实现
		chess2.addEventListener('click', burtyang.onClick);

		//赢法数组初始化
		for(var i=0; i<15; i++){
			wins_arr[i] = [];
			for(var j=0; j<15; j++){
				wins_arr[i][j] = [];
			}
		}

		//统计所有的横线赢法
		for(var i=0; i<15; i++){
			for(var j=0; j<11; j++){
				for(var k=0; k<5; k++){
					wins_arr[i][j+k][win_index] = true;
				}
				/**
				 * 第0中赢法，最后一位表示第0种
				 * 前两位表示坐标，
				 * 正好[0,0],[0,1],[0,2],[0,3],[0,4]五个坐标连成一条线
				 * **/
				//wins_arr[0][0][0] =  true
				//wins_arr[0][1][0] =  true
				//wins_arr[0][2][0] =  true
				//wins_arr[0][3][0] =  true
				//wins_arr[0][4][0] =  true
	
				//第1中赢法
				//wins_arr[0][1][1] =  true
				//wins_arr[0][2][1] =  true
				//wins_arr[0][3][1] =  true
				//wins_arr[0][4][1] =  true
				//wins_arr[0][5][1] =  true
				win_index++;
			}
		}
		//统计所有的竖线赢法
		for(var i=0; i<15; i++){
			for(var j=0; j<11; j++){
				for(var k=0; k<5; k++){
					wins_arr[j+k][i][win_index] = true;
				}
				win_index++;
			}
		}
		//统计所有的正斜线赢法
		for(var i=0; i<11; i++){
			for(var j=0; j<11; j++){
				for(var k=0; k<5; k++){
					wins_arr[i+k][j+k][win_index] = true;
				}
				win_index++;
			}
		}
		//统计所有的反斜线赢法
		for(var i=0; i<11; i++){
			for(var j=14; j>3; j--){
				for(var k=0; k<5; k++){
					wins_arr[i+k][j-k][win_index] = true;
				}
				win_index++;
			}
		}
		//console.log(win_index)共573种赢法

		//初始化赢法统计数组
		for(var i=0; i<win_index; i++){
			myWin[i] = 0;
			computerWin[i] = 0;
		}
	}

	burtyang.startGame = function(){
		this.init();
		lastframetime = Date.now();
		this.gameLoop();
	}

	burtyang.gameLoop = function(){
		requestAnimationFrame(burtyang.gameLoop);
		var now = Date.now();
		diffframetime = now - lastframetime; //两帧之间之间差(毫秒)
		lastframetime = now;
	}
	//绘制棋盘
	burtyang.drawChess = function(){
			
		ctx1.drawImage(backgroundPic, 0, 0, can_w, can_h);
		ctx1.save();
		ctx1.strokeStyle = '#2a2929';  //画线颜色
		ctx1.beginPath();
		for(var i=margin_space; i<can_w; i+=increse_space){
			//绘制横线
			ctx1.moveTo(margin_space, i);
			ctx1.lineTo(can_w-margin_space, i);  
			//绘制竖线
			ctx1.moveTo(i, margin_space);
			ctx1.lineTo(i, can_w-margin_space);
		}
		ctx1.stroke();
		ctx1.closePath();
		ctx1.restore();
	}

	/**绘制棋子
	 * x坐标
	 * y坐标
	 * 棋子颜色, 默认黑色棋子
	****/
	burtyang.drawChessMan = function(x=0, y=0){
		var r_x = margin_space + x *increse_space;  //圆心x坐标
		var r_y = margin_space + y *increse_space;  //圆心y坐标
		ctx2.save();
		ctx2.beginPath();
		//创建渐变，中心点稍微便宜到右上角
		var grd=ctx2.createRadialGradient(r_x+2 ,r_y-2, 13 ,r_x+2,r_y-2,0); 
		if(chessColor){
			grd.addColorStop(0, '#0A0A0A');
			grd.addColorStop(1, '#636766');
		}else{
			grd.addColorStop(0, '#D1D1D1');
			grd.addColorStop(1, '#F9F9F9');
		}
		
		ctx2.arc(r_x,r_y, 13, 0, 2*Math.PI);
		ctx2.fillStyle = grd;
		ctx2.fill();
		ctx2.closePath();
		ctx2.restore();
	}

	//计算机AI自动下棋
	burtyang.computerAI = function(){
		var myScore = [];  //我方得分
		var computerScore = [];  //计算机得分
		var maxScore =0;  //计算最高分数
		var x_pos = 0, y_pos = 0; //保存最高分点的坐标
		//初始化得分
		for(var i=0; i<15; i++){
			myScore[i] = [];
			computerScore[i] = [];
			for(var j=0; j<15; j++){
				myScore[i][j] = 0;
				computerScore[i][j] = 0;
			}
		}

		//遍历整个棋盘
		for(var i=0; i<15; i++){
			for(var j=0; j<15; j++){
				//是否有一个元素满足坐标相等
				let pass = chessBoard.some(function(ele, index){
					return (ele.x==i && ele.y==j);
				});
				if(!pass){  //表示该点未落下棋子，为空闲点
					for(var k=0; k<win_index; k++){
						if(wins_arr[i][j][k]){  //该落下点是有价值的，可以赢的
							//对黑色棋子进行拦截
							switch(myWin[k]){
								case 1: myScore[i][j] += 200;  
										break;
								case 2: myScore[i][j] += 400;  
										break;
								case 3: myScore[i][j] += 2000;  
										break;
								case 4: myScore[i][j] += 10000;  
										break;
							}
							//使计算机落下棋子更有效
							switch(computerWin[k]){
								case 1: computerScore[i][j] += 220;  
										break;
								case 2: computerScore[i][j] += 420;  
										break;
								case 3: computerScore[i][j] += 2100;  
										break;
								case 4: computerScore[i][j] += 20000;  
										break;
							}
						}
					}
					//得到了最高分数的点
					if(myScore[i][j] > maxScore){
						maxScore = myScore[i][j];
						x_pos = i;
						y_pos = j;
					}else if(myScore[i][j] == maxScore){
						if(computerScore[i][j] > computerScore[x_pos][y_pos]){
							x_pos = i;
							y_pos = j;
						}
					}
					if(computerScore[i][j] > maxScore){
						maxScore = computerScore[i][j];
						x_pos = i;
						y_pos = j;
					}else if(computerScore[i][j] == maxScore){
						if(myScore[i][j] > myScore[x_pos][y_pos]){
							x_pos = i;
							y_pos = j;
						}
					}
				}
			}
		}
		burtyang.drawChessMan(x_pos, y_pos, false);
		var tmp_obj = {
			x: x_pos, 
			y: y_pos,
			color:2  //2 表示下的是白色
		}
		chessBoard.push(tmp_obj);  //落子
		//遍历所有赢法
		for(var k=0; k<win_index; k++){
			if(wins_arr[x_pos][y_pos][k]){
				computerWin[k]++;
				myWin[k] = 6; //我方这种赢法不可能赢
				if(computerWin[k]===5){ //这种赢法正好有5个棋子，表示赢了
					console.log('计算机超级牛逼啊，我被打败了');
					winer.innerHTML = '计算机赢啦';
					winer.style.display = 'block';
					reStart.style.display = 'block';
					gameOver = true;
					break;
				}
			}
		}
		if(!gameOver){
			chessColor = !chessColor; //取反
		}
	}

	//点击画布二
	burtyang.onClick = function(e){
		if(gameOver && !chessColor){
			return;
		}
		var event = e || window.event;
		var clientX = event.offsetX;
		var clientY = event.offsetY;
		//棋子索引
		clientX = (clientX-15)<0? 0: (clientX-15);
		clientY = (clientY-15)<0? 0: (clientY-15);
		var x = (clientX / increse_space).toFixed();
		var y = (clientY / increse_space).toFixed();

		var tmp_obj = {
			x: x, 
			y: y,
			color:1  //1 表示下的是黑色
		}
		//是否有一个元素满足坐标相等
		var pass = chessBoard.some(function(ele, index){
			return (ele.x==x && ele.y==y);
		});
		if(!pass){
			chessBoard.push(tmp_obj);  //该坐标没有被使用，可以落子
			burtyang.drawChessMan(x,y);

			//遍历所有赢法
			for(var k=0; k<win_index; k++){
				if(wins_arr[x][y][k]){
					myWin[k]++;
					computerWin[k] = 6; //计算机这种赢法不可能赢
					if(myWin[k]===5){ //这种赢法正好有5个棋子，表示赢了
						console.log('我方胜利');
						winer.innerHTML = '还是我厉害,赢啦';
						winer.style.display = 'block';
						reStart.style.display = 'block';
						gameOver = true;
						break;
					}
				}
			}
			if(!gameOver){
				chessColor = !chessColor; //取反
				burtyang.computerAI();  //计算机自动下棋
			}
		}
	}

	//重玩游戏
	burtyang.reStart = function(){
		//清除画布2
		ctx2.clearRect(0, 0, can_w, can_h);
		chessBoard = [];
		chessColor = true;  //棋子颜色， 默认开始为黑色
		//赢法的统计数组
		gameOver = false;  //游戏结束
		//初始化赢法统计数组
		for(var i=0; i<win_index; i++){
			myWin[i] = 0;
			computerWin[i] = 0;
		}

	}

	//点击重新玩游戏
	reStart.addEventListener('click', ()=>{
		winer.style.display = 'none';
		reStart.style.display = 'none';
		burtyang.reStart();
	});


	burtyang.startGame();

})();